package com.centersoft.flowable.db.model.gateway.impl;

import com.centersoft.flowable.core.model.FlowModelModel;
import com.centersoft.flowable.core.model.QueryTaskRequest;
import com.centersoft.flowable.core.web.gateway.FlowModelGateway;
import com.centersoft.flowable.db.model.FlowModelConvert;
import com.centersoft.flowable.db.model.dao.FlowModelDao;
import com.centersoft.flowable.db.model.entity.FlowModelEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author wangzhiqiang
 * @since 2025/4/5 17:53
 */
@Component
public class FlowModelGatewayImpl implements FlowModelGateway {
    private final FlowModelDao flowModelDao;

    public FlowModelGatewayImpl(FlowModelDao flowModelDao) {
        this.flowModelDao = flowModelDao;
    }

    @Override
    public List<FlowModelModel> listModel(QueryTaskRequest request) {
        // 当为多组织时,需要通过组织编号,菜单编号和项目编号来获取对应的流程发布实例
        String sql = "select  dm.* from act_de_model dm,act_re_procdef rp where rp.KEY_ = dm.model_key and  CATEGORY_ =:menuCode ";


        Map<String ,Object> params=new HashMap<>();
        params.put("menuCode", request.getMenuCode());

        if (StringUtils.isNotBlank(request.getTenantId())){
            sql+=" and dm.tenant_id =:tenantId";
            params.put("tenantId", request.getTenantId());
        }
        if (StringUtils.isNotBlank(request.getOrgCode())){
            sql+=" and orgCode=:orgCode";
            params.put("orgCode", request.getOrgCode());
        }
        sql+=" ORDER BY rp.VERSION_ desc ";


        List<FlowModelEntity> flowModelEntities = flowModelDao.queryBySql(sql, params, FlowModelEntity.class);



        return flowModelEntities.stream().map(FlowModelConvert::toModel).collect(Collectors.toList());
    }
}
